package com.bitjiuyeke;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Scanner;

public class Demo04_Insert {
    public static void main(String[] args) {
        //定义mysql数据源
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        //设置数据库的连接串
        mysqlDataSource.setURL("jdbc:mysql://localhost:3306/java116");
        //设置用户名和密码
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("123456");
        //定义jdbc数据源对象
        DataSource dataSource = mysqlDataSource;

        //声明数据库连接对象
        Connection connection = null;
        //声明sql语句预处理对象
        PreparedStatement statement = null;
        //声明查询结果集对象
        ResultSet resultSet = null;
        try {//1获取数据库连接
            connection = dataSource.getConnection();
            //2定义sql语句
            String sql = "insert into student (name,sno,age,gender,enroll_date,class_id) values(?,?,?,?,?,?) "; // 占位符替换
            // 3获取sql预处理对象
            statement = connection.prepareStatement(sql);
            // 接收用户输入的姓名
            Scanner scanner = new Scanner(System.in);
            String inputname = scanner.next();
            String inputsno=scanner.next();
            int inputage=scanner.nextInt();
            String inputgender=scanner.next();
            String inputenroll_date=scanner.next();
            int inputclass_id=scanner.nextInt();
            // 4设置参数
            statement.setString(1, inputname);
            statement.setString(2, inputsno);
            statement.setInt(3, inputage);
            statement.setString(4, inputgender);
            statement.setString(5, inputenroll_date);
            statement.setInt(6, inputclass_id);

            // 5执行sql语句
            int row = statement.executeUpdate();
            // 获取查询结果集
            // 6遍历一条结果集，使用if语句
            if (row==1 ) { // resultSet.next()返回true则有下一行数据，false则没有
                // 获取数据列
                System.out.println("数据插入成功！");
            }else {
                System.out.println("数据插入失败！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 7关闭资源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
